'''
Created on 2009-10-5

@author: ray
'''

class Host(object):

    def __init__(self, userName="", hostName="", addr="", portNo=0):
        #Cryto Communication is not supproted at the moment!
        self.userName   = userName
        self.hostName   = hostName
        self.addr       = addr
        self.portNo     = portNo
        self.nickName   = ""
        self.groupName  = ""
        self.hostStatus = 0L
        self.updateTime = ""
        self.priority   = 0
    
    def __str__(self):
        return "userName = %s\r\nhostName = %s\r\naddress = %s:%d" % (self.userName, self.hostName, self.addr, self.portNo)
    
    def __eq__(self, h):
        if h.addr == self.addr and h.portNo == self.portNo:
            return True
        else:
            return False

class HostsMgr(object):
    
    def __init__(self):
        
        self.hosts = []
        self._iter = iter(self.hosts)
        
    def __str__(self):
        return "\n".join([str(h) for h in self.hosts])
    
    def __iter__(self):
        return self
    
    def next(self):
        return self._iter.next()
    
    def cmp(self, host1, host2):
        if host1.addr > host2.add:
            return 1
        if host1.addr < host2.addr:
            return -1
        if host1.portNo > host2.portNo:
            return 1
        if host1.portNo < host2.portNo:
            return -1
        return 0
    
    def search(self, addr, portNo):
        for h in self.hosts:
            if h.addr == addr and h.portNo == portNo:
                return h
        return None
    
    def addHost(self, host):
        h = self.search(host.addr, host.portNo)
        if h:
            idx = self.hosts.index(h)
            self.hosts[idx] = host
        else:
            self.hosts.append(host)
        return True
    
    def delHost(self, addr, portNo):
        h = self.search(addr, portNo)
        if h:
            self.hosts.remove(h)
            return True
        else:
            return False
        
    def hostCount(self):
        return len(self.hosts)
        
    def getByName(self, userName):
        for h in self.hosts:
            if h.userName == userName:
                return h
        return None

    def getByAddr(self, addr):
        for h in self.hosts:
            if h.addr == addr:
                return h
        return None

    def getByIndex(self, index):
        if index < self.hostCount():
            return self.hosts[index]
        else:
            return None
    
    def sort(self):#implement later
        pass    
